
import {Space, Button, message, Divider ,Modal} from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import CreateForm from './components/CreateForm';
import UpdateForm from './components/UpdateForm';
import { PlusOutlined ,ExclamationCircleOutlined} from '@ant-design/icons';
import { queryDriver, addDriver, updateDriver, removeDriver,batchRemoveDriver } from '@/services/driver';

const { confirm } = Modal;
import styles from '@/global.less';


/**
 * 添加节点
 * @param fields
 */
const handleAdd = async (fields: any,resetForm: any) => {
  const hide = message.loading('正在添加');
  try {
    console.log(fields)
    await addDriver(fields);
    hide();
    resetForm();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};

/**
 * 更新节点
 * @param fields
 */
const handleUpdate = async (fields: any,resetForm: any) => {
  const hide = message.loading('正在保存');
  try {
    await updateDriver(fields);
    hide();
    resetForm();
    message.success('保存成功');
    return true;
  } catch (error) {
    hide();
    message.error('保存失败请重试！');
    return false;
  }
};

//删除单个
const remove = async (id: number) => {
  const hide = message.loading('正在删除');
  try {
    await removeDriver({ id });
    hide();

    message.success('删除成功，正在刷新！');

    return true;
  } catch (error) {
    hide();
    message.error('删除失败请重试！');
    return false;
  }
};





const DeviceAttr: React.FC = () => {

const [createModalVisible, handleModalVisible] = useState<boolean>(false);
const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
const [formValues, setFormValues] = useState({});




const actionRef = useRef<ActionType>();
  const columns: ProColumns[] = [   
    {
    title: 'ID',
    search: false,
    dataIndex: 'id',
  },
  {
    title: '名称',
    dataIndex: 'name',
  },
   {
      title: '驱动类型',
      dataIndex: 'driverType',
      valueEnum: {0:'网口',1:'串口'},
    },
    {
      title: '串口号',
      dataIndex: 'commandPort',
      search:false,
    },
    {
      title: '波特率',
      dataIndex: 'baudRate',
      search:false,
    },
    {
      title: '数据位',
      dataIndex: 'dataBits',
      search:false,
    },
    {
      title: '停止位',
      dataIndex: 'stopBits',
      search:false,
    },
    {
      title: '校验位',
      dataIndex: 'parity',
      search:false,
      valueEnum: {1:'奇',2:'偶',0:'无'},
    },
    {
      title: 'ip和端口',
      dataIndex: 'ipport',
      search:false,
    },
    {
      title: '操作',
      valueType: 'option',
      render: (text, record, _, action) => (
       <> <a
          key="editable"
          onClick={async () => {
            handleUpdateModalVisible(true);
            setFormValues(record);
          }}
        >
          编辑
        </a><Divider type="vertical" />
          <a onClick={() => {
            confirm({
              title: '您确定要删除吗?',
              icon: <ExclamationCircleOutlined />,
              async onOk() {
                await remove(record.id);
                actionRef.current?.reload();
              },
              onCancel() {
                console.log('Cancel');
              },
            });
          }}
          >
            删除
          </a></>
      )
    },
  ];


  const [selectedRowKeys,setSelectedRowKeys] = useState<number[]>([]);
  const onSelectChange = async (sKeys ) => {
    setSelectedRowKeys(sKeys);

  };
  
//批量删除
const batchRemove = async () => {
  const hide = message.loading('正在删除');
  try {
    await batchRemoveDriver({ ids: selectedRowKeys.join(',')});
    setSelectedRowKeys([]);
    hide();
    message.success('删除成功，正在刷新！');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败请重试！');
    return false;
  }
};

  return (
    <>
      <ProTable
        rowKey="id"
        toolBarRender={(action, { selectedRows }) => [
          <Button icon={<PlusOutlined />} type="primary"  className={styles.addBtn} onClick={() => handleModalVisible(true)}>
            新增
          </Button>,
       
        ]}
        rowSelection={{selectedRowKeys,onChange: onSelectChange}}
        tableAlertRender={({ selectedRowKeys, selectedRows, onCleanSelected }) => (
          <Space size={24}>
            <span>
              已选 {selectedRowKeys.length} 项
              <a style={{ marginLeft: 8 }} onClick={onCleanSelected}>
                取消选择
              </a>
            </span>
          </Space>
        )}
        tableAlertOptionRender={() => {
          return (
            <Space size={16}>
              <a  onClick={() => {
              confirm({
                title: '您确定要批量删除吗?',
                icon: <ExclamationCircleOutlined />,
                async onOk() {
                  await batchRemove();
                  actionRef.current?.reload();
                },
                onCancel() {
                  console.log('Cancel');
                },
              });
            }} >批量删除</a>
              {/* <a>导出数据</a> */}
            </Space>
          );
        }}
        search={{
          labelWidth: 'auto',
        }}
        options={false}
        actionRef={actionRef}
      
        columns={columns}
        request={(params) => queryDriver(params)}
      />
     <CreateForm
        onSubmit={async (value,resetForm) => {
          const success = await handleAdd(value,resetForm);
          if (success) {
            handleModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => handleModalVisible(false)}
        modalVisible={createModalVisible}
       
      />
      {formValues && Object.keys(formValues).length ? (
        <UpdateForm
          onSubmit={async (value,resetForm) => {
            const success = await handleUpdate(value,resetForm);
            if (success) {
              handleModalVisible(false);
              setFormValues({});
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          onCancel={() => {
            handleUpdateModalVisible(false);
            setFormValues({});
          }}
          updateModalVisible={updateModalVisible}
          values={formValues}
       
        />
      ) : null}
    </>
  );
};

export default DeviceAttr;



